package cn.boot.asyncmy.controller;

import cn.boot.asyncmy.common.vo2.ExecuteDTO;
import cn.boot.asyncmy.dao.MemberRepository;
import cn.boot.asyncmy.entity.Member;
import cn.boot.asyncmy.service.AsyncService;
import cn.boot.asyncmy.service.MemberService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author liangxin
 * @since 29/08/2018
 */
@RestController
@RequestMapping("member")
public class MemberController {
    private static Log logger = LogFactory.getLog(MemberController.class);

    @Autowired
    private MemberRepository repository;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AsyncService asyncService;

    //service层中拦截方案  无法成功
    @PostMapping("saveBatchOfService")
    public ExecuteDTO saveBatchOfService() {
        String path = "D:\\98\\test2SaveData.txt";
        asyncService.writeCode3(path);
        return new ExecuteDTO(true, "保存成功", null);
    }

    /**  controller层拦截 防止excel重复数据导入到数据库 初显成效
     * {
     *   "id": "",
     *   "idCard": "98",
     *   "date": " ",
     *   "name": "demoData1",
     *   "place": "demoData2",
     *   "sex": 1
     * }
     */
    @PostMapping("saveBatch")
    public ExecuteDTO saveBatch() {
        String path = "D:\\98\\test2SaveData.txt"; // \src\main\resources

        File file = new File(path);
        List<String> list = null;
        try {
            list = FileUtils.readLines(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        int count = 0;
        for (String string : list) {
            String[] parmas = string.split("，");
            Member vo = new Member();
//          vo.setDate(DateUtils.parseDate(parmas[0], "yyyy-MM-dd"));//date == null   date = new Date();
            vo.setName(parmas[1]);
            vo.setPlace(parmas[2]);
            vo.setSex(StringUtils.isBlank(parmas[3]) ? 0 : Integer.parseInt(parmas[3]));
            vo.setIdCard(parmas[4]);
            try {
                memberService.saveMember(vo);
            } catch (DataIntegrityViolationException e) { //捕获违反unique异常，跳过此条重复数据
                logger.info("--->e1-" +  e.getMessage());
                if(e.getCause()!=null && (e.getCause() instanceof ConstraintViolationException)){
//                    throw (ConstraintViolationException)e.getCause();
//                    continue;
                }else{
                    logger.info("--->e2-" +  e.getMessage());

                }
            }
            count++;
            logger.info("--->完成第-" + count + "-条导入");
        }
        return new ExecuteDTO(true, "保存成功", null);
    }

    /**
     * {
     *   "id": "",
     *   "idCard": "98",
     *   "date": " ",
     *   "name": "demoData1",
     *   "place": "demoData2",
     *   "sex": 1
     * }
     */
    @PostMapping("save")
    public ExecuteDTO save(@RequestBody Member entity) {
        if (entity.date == null) {
            entity.date = new Date();
        }
        try {
//            repository.save(entity);//id为null 自动创建
            memberService.saveMember(entity);
        } catch (Exception e) {
            System.out.println("----------------->______________________");
            e.printStackTrace();
        }
        return new ExecuteDTO(true, "保存成功", entity.id);
    }

    // http://localhost:1911/member/
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView getUserById(Model model) {
        return new ModelAndView("member/memberList.html");
    }


    @GetMapping("get/{id}")
    public Member get(@PathVariable String id) {
        Optional<Member> bean = repository.findById(id);
        return bean.get();
    }

    @GetMapping("remove/{id}")
    public ExecuteDTO remove(@PathVariable String id) {
        repository.deleteById(id);
        return new ExecuteDTO(true, "删除成功", id);
    }

}

